package com.aiguigu.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PolandNotation {
    public static void main(String[] args) {
        String suffixExpression = "3 4 + 5 * 6 -";
        List<String> list = getList(suffixExpression);
        int calculate = calculate(list);
        System.out.println(calculate);
    }
    public  static List<String> getList(String expression){
        String [] split =expression.split(" ");
        List<String> list = new ArrayList<>();

        for (String s : split) {
            list.add(s);
        }
        return list;
    }

    public static int calculate(List<String> list){
       Stack<String>stack = new Stack<>();
        for (String s : list) {
            if (s.matches("\\d+")){
                stack.push(s);
            }else {
                int number2 = Integer.parseInt(stack.pop());
                int number1 = Integer.parseInt(stack.pop());
                int res = 0;
                if (s.equals("+")){
                    res =number1+number2;
                }else if (s.equals("-")){
                    res = number1-number2;
                }else  if (s.equals("*")){
                    res = number1*number2;
                }else if (s.equals("/")){
                    res = number1/number2;
                }else {
                    throw new RuntimeException("运算符有误");
                }
                stack.push(""+res);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}
